package com.naruto.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.naruto.dao.AdminMapper;
import com.naruto.dao.BaseMapper;
import com.naruto.dao.GroupAccessMapper;
import com.naruto.dao.GroupRuleMapper;
import com.naruto.entity.AdminEntity;
import com.naruto.entity.GroupAccessEntity;
import com.naruto.entity.GroupRuleEntity;
import com.naruto.mbean.UrlBean;
import com.naruto.response.BaseResponse;
import com.naruto.response.UrlResp;
import com.naruto.tools.StringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import tk.mybatis.mapper.entity.Example;

@RestController
@Api(value = "菜单模块")
@RequestMapping("menu")
public class MenuController {
	@Autowired
	AdminMapper schoolMapper;
	@Autowired
	GroupRuleMapper groupRuleMapper;
	@Autowired
	GroupAccessMapper groupAccessMapper;

//	@ApiOperation(value = "菜单列表", notes = "")
//	@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
//			@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
//	@RequestMapping(value = { "/menuList" }, method = RequestMethod.GET)
//	public String login(@RequestBody AdminEntity admin) {
//		// List<AdminEntity> entitys = schoolMapper.selectAll();
//		Example example = new Example(AdminEntity.class);
//		example.createCriteria().andEqualTo("username", admin.getPassword()).andEqualTo("password",
//				admin.getPassword());
//		AdminEntity entitys = schoolMapper.selectOneByExample(example);
//		if (entitys != null) {
//			String token = StringUtil.GetGUID();
//			entitys.setTokenId(token);
//			schoolMapper.updateByExample(entitys, example);
//			AdminLoginResp adminLoginResp = new AdminLoginResp();
//			adminLoginResp.setAdmin(entitys);
//			adminLoginResp.setStatus("0");
//			adminLoginResp.setResultMsg("登录成功");
//			String json = JSON.toJSONString(adminLoginResp);
//			return json;
//		} else {
//			AdminLoginResp adminLoginResp = new AdminLoginResp();
//			adminLoginResp.setStatus("-1");
//			adminLoginResp.setResultMsg("登录失败");
//			String json = JSON.toJSONString(adminLoginResp);
//			return json;
//		}
//	}

	// 1、创建权限组

	// 2 获取路由记录
	@ApiOperation(value = "获取路由记录", notes = "")
	@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
			@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
	@RequestMapping(value = { "/urlList" }, method = RequestMethod.POST)
	public String getUrls(HttpServletRequest request) {

		ServletContext servletContext = request.getSession().getServletContext();
		if (servletContext == null) {
			return null;
		}
		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(servletContext);

		RequestMappingHandlerMapping rmhp = wc.getBean(RequestMappingHandlerMapping.class);
		Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
		List<UrlBean> urlBeans = new ArrayList<UrlBean>();
		for (Iterator<RequestMappingInfo> iterator = map.keySet().iterator(); iterator.hasNext();) {
			RequestMappingInfo info = iterator.next();
			if (info.getMethodsCondition() != null && !info.getMethodsCondition().toString()
					.substring(1, info.getMethodsCondition().toString().length() - 1).isEmpty()) {
				UrlBean urlBean = new UrlBean();
				urlBean.setRequesrUrl(info.getPatternsCondition().toString().substring(1,
						info.getPatternsCondition().toString().length() - 1));
				urlBean.setRequestMethod(info.getMethodsCondition().toString().substring(1,
						info.getMethodsCondition().toString().length() - 1));
				urlBeans.add(urlBean);
				// HandlerMethod method = map.get(info);
				// System.out.print(method.getMethod().getName() + "--");
				// System.out.println();
			}

		}
		UrlResp adminLoginResp = new UrlResp();
		adminLoginResp.setStatus("0");
		adminLoginResp.setResultMsg("成功请求");
		adminLoginResp.setUrlBeans(urlBeans);
		String json = JSON.toJSONString(adminLoginResp);
		return json;
	}

	// 2、1绑定权限组与路由 操作
	@ApiOperation(value = "绑定权限组与路由操作", notes = "")
	@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
			@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
	@RequestMapping(value = { "/bingdGourp/{groupId}" }, method = RequestMethod.POST)
	public String bingdGourp(@PathVariable String groupId, @RequestBody List<GroupRuleEntity> groupAccessEntitys) {
		// //插入记录或更新记录
		// Example example =new Example(AdminEntity.class);
		// example.createCriteria().andEqualTo("token",token);
		// AdminEntity entitys = schoolMapper.selectOneByExample(example);
		for (GroupRuleEntity groupAccessEntity : groupAccessEntitys) {
			groupAccessEntity.setGroupId(groupId);
			groupAccessEntity.setAuth("0");
			groupRuleMapper.insert(groupAccessEntity);
		}
		BaseResponse adminLoginResp = new BaseResponse();
		adminLoginResp.setStatus("0");
		adminLoginResp.setResultMsg("成功请求");
		String json = JSON.toJSONString(adminLoginResp);
		return json;
	}

	// 3、绑定权限与用户
	@ApiOperation(value = "绑定权限组与用户", notes = "")
	@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"),
			@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
	@RequestMapping(value = { "/bingdUser/{uid}/{groupid}" }, method = RequestMethod.POST)
	public String bingdUser(@PathVariable String uid,@PathVariable String groupid) {
		// //插入记录或更新记录
		
		//查一下是否有绑定过了
		Example example = new Example(GroupAccessEntity.class);
		example.createCriteria().andEqualTo("uid", uid);
		GroupAccessEntity entitys = groupAccessMapper.selectOneByExample(example);
		System.out.println(entitys.toString());
		if(entitys != null) 
		{
			GroupAccessEntity groupAccessEntity =new GroupAccessEntity();
			groupAccessEntity.setGroupId(groupid);
			groupAccessEntity.setUid(uid);
			groupAccessMapper.updateByExampleSelective(groupAccessEntity,example);
		}else {
			GroupAccessEntity groupAccessEntity =new GroupAccessEntity();
			groupAccessEntity.setGroupId(groupid);
			groupAccessEntity.setUid(uid);
			groupAccessMapper.insertSelective(groupAccessEntity);
		}
		
		BaseResponse adminLoginResp = new BaseResponse();
		adminLoginResp.setStatus("0");
		adminLoginResp.setResultMsg("成功请求");
		String json = JSON.toJSONString(adminLoginResp);
		return json;
	}
	
	
	/**
	    String sql = "select g.* from auth_group g, auth_group_access a where g.id= a.groupId";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql);
		List<Map<String, Object>> list =basicMapper.fetch(paramMap);
		JSONArray arr =new JSONArray();
		for (Map<String, Object> map : list) {
			arr.add(map);
		}
	 */
}
